package cn.raven.pet.service.impl;

import cn.raven.pet.domain.PetType;
import cn.raven.pet.mapper.PetTypeMapper;
import cn.raven.pet.service.IPetTypeService;
import cn.raven.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Raven
 * @since 2022-07-16
 */
@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {
    @Autowired
    private PetTypeMapper petTypeMapper;
    @Override
    public List<PetType> tree() {
        //获取所有数据
        List<PetType> petTypes = petTypeMapper.findAll();
        //创建一个装最终结果的集合
        List<PetType> petTypeList =  new ArrayList<PetType>();
        //为了解决时间复杂度，转为map
        /*  转换为map集合，stream模式
 Map<Long, PetType> petTypeMap = petTypes.stream().collect(Collectors.toMap(PetType::getId, item -> item));
       */
        Map<Long, PetType> petTypeMap = new HashMap<>();
        for(PetType petType : petTypes){
            petTypeMap.put(petType.getId(),petType);
        }
        //先把一级数据找出来
        for (PetType petType : petTypes){
            if (petType.getPid() == null){
                petTypeList.add(petType);
            }else {
                PetType petTypeParent = petTypeMap.get(petType.getPid());
                if (petTypeParent != null){
                    petTypeParent.getChildren().add(petType);
                }
            }
        }
        return petTypeList;
    }

    @Override
    public void add(PetType petType) {
        petTypeMapper.add(petType);
        String dirPath = "";
        //先在mapper.xml中返回自增id,在判断他有没有上级部门
        if (petType.getParent().getId() == null){
            dirPath = "/"+petType.getId();
        }else {
            Long id = petType.getParent().getId();
            PetType parentPetType = petTypeMapper.findOne(id);
            if(parentPetType != null) {
                dirPath = parentPetType.getDirPath() + "/" + petType.getId();
            }
        }
        petType.setDirPath(dirPath);
        petTypeMapper.update(petType);
    }

    @Override
    public void update(PetType petType) {
        String dirPath = "";
        //先在mapper.xml中返回自增id,在判断他有没有上级部门
        if (petType.getParent().getId() == null){
            dirPath = "/"+petType.getId();
        }else {
            Long id = petType.getParent().getId();
            PetType parentPetType = petTypeMapper.findOne(id);
            if(parentPetType != null) {
                dirPath = parentPetType.getDirPath() + "/" + petType.getId();
            }
        }
        petType.setDirPath(dirPath);
        petTypeMapper.update(petType);
    }
}
